package org.hsieh.tr.explore.dbsource.impl;

import java.sql.Connection;
import java.util.List;

import org.hsieh.tr.explore.annotation.TreeNodeChildren;
import org.hsieh.tr.explore.annotation.TreeNodeLabel;
import org.hsieh.tr.explore.dbconn.ConnectionFactory;
import org.hsieh.tr.explore.dbsource.IDatabaseInfo;
import org.hsieh.tr.explore.dbsource.ISchemaEntity;

/**
 * 
 * 
 *@author hsieh 234aini@gmail.com
 * 
 */
public class DatabaseInfoImpl extends AbstractDBObj implements IDatabaseInfo {

    public String name;

    public String userName;

    public String password;

    public String driverClassName;

    public List<String> driverClassPath;

    public String port;

    public String dbName;

    public String connectUrl;

    public String getDbName() {
	return dbName;
    }

    public void setDbName(String dbName) {
	this.dbName = dbName;
    }

    public String getPort() {
	return port;
    }

    public void setPort(String port) {
	this.port = port;
    }

    public String composeUrl() {
	String portStr = (this.port == null || this.port.equals("")) ? "" : ":"
		+ port;
	// example: jdbc:mysql://localhost:3306/dbname
	return String.format("%s%s/%s", getConnectUrl(), portStr, getDbName());
    }

    public String getName() {
	if (name == null) {
	    return composeUrl();
	}
	return name;
    }

    public String getUserName() {
	return userName;
    }

    public void setUserName(String userName) {
	this.userName = userName;
    }

    public String getPassword() {
	return password;
    }

    public void setPassword(String password) {
	this.password = password;
    }

    public String getDriverClassName() {
	return driverClassName;
    }

    public void setDriverClassName(String driverClassName) {
	this.driverClassName = driverClassName;
    }

    public List<String> getDriverClassPath() {
	return driverClassPath;
    }

    public void setDriverClassPath(List<String> driverClassPath) {
	this.driverClassPath = driverClassPath;
    }

    public void setName(String name) {
	this.name = name;
    }

    public String getConnectUrl() {
	return connectUrl;
    }

    public void setConnectUrl(String connectUrl) {
	this.connectUrl = connectUrl;
    }

    @TreeNodeLabel(image = "icons/database-16x16.png")
    public String displayLabel() {
	return String.format("%s(%s)", getName(), getConnectUrl().substring(
		getConnectUrl().lastIndexOf("//") + 2));
    }

    @TreeNodeChildren
    public List<ISchemaEntity> getSchemas() throws Exception {
	Connection connect = ConnectionFactory.connect(this);
	setMetaData(connect.getMetaData());
	return findSchemaEntities();
    }
}
